const express = require('express');
const { pool } = require('../config/db');
const { authMiddleware } = require('../middleware/auth');
const llmService = require('../services/llmService');

const router = express.Router();

// 所有接口都需要认证
router.use(authMiddleware);

/**
 * PUT /api/personnel/:id
 * 更新人员信息
 */
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    console.log(`更新人员信息，ID: ${id}`);

    // 检查记录是否存在
    const [checkRows] = await pool.execute(
      'SELECT * FROM processed_personnel WHERE raw_personnel_id = ?',
      [id]
    );

    if (checkRows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '记录不存在'
      });
    }

    // 格式化日期函数
    const formatDateForDB = (dateValue) => {
      if (!dateValue) return null;
      
      try {
        if (typeof dateValue === 'string') {
          // ISO格式：2024-01-01T00:00:00.000Z -> 2024-01-01
          if (dateValue.includes('T')) {
            return dateValue.split('T')[0];
          }
          // 已经是正确格式
          return dateValue;
        }
        return dateValue;
      } catch (error) {
        console.warn('日期格式化失败:', dateValue, error);
        return null;
      }
    };

    // 处理数据：空值转null
    const processedData = {
      country_region: updateData.country_region || null,
      chinese_name: updateData.chinese_name || null,
      english_name: updateData.english_name || null,
      gender: updateData.gender || null,
      birth_date: formatDateForDB(updateData.birth_date),
      age: updateData.age || null,
      email: updateData.email || null,
      phone: updateData.phone || null,
      graduate_school: updateData.graduate_school || null,
      education_level: updateData.education_level || null,
      military_branch: updateData.military_branch || null,
      military_rank: updateData.military_rank || null,
      organization: updateData.organization || null,
      current_position: updateData.current_position || null,
      position_start_date: formatDateForDB(updateData.position_start_date),
      work_status: updateData.work_status || null,
      work_experience_cn: updateData.work_experience_cn || null,
      education_experience_cn: updateData.education_experience_cn || null,
      chinese_biography: updateData.chinese_biography || null,
      english_biography: updateData.english_biography || null
    };

    // 更新数据
    const updateSql = `
      UPDATE processed_personnel
      SET 
        country_region = ?,
        chinese_name = ?,
        english_name = ?,
        gender = ?,
        birth_date = ?,
        age = ?,
        email = ?,
        phone = ?,
        graduate_school = ?,
        education_level = ?,
        military_branch = ?,
        military_rank = ?,
        organization = ?,
        current_position = ?,
        position_start_date = ?,
        work_status = ?,
        work_experience_cn = ?,
        education_experience_cn = ?,
        chinese_biography = ?,
        english_biography = ?,
        updated_at = NOW()
      WHERE raw_personnel_id = ?
    `;

    await pool.execute(updateSql, [
      processedData.country_region,
      processedData.chinese_name,
      processedData.english_name,
      processedData.gender,
      processedData.birth_date,
      processedData.age,
      processedData.email,
      processedData.phone,
      processedData.graduate_school,
      processedData.education_level,
      processedData.military_branch,
      processedData.military_rank,
      processedData.organization,
      processedData.current_position,
      processedData.position_start_date,
      processedData.work_status,
      processedData.work_experience_cn,
      processedData.education_experience_cn,
      processedData.chinese_biography,
      processedData.english_biography,
      id
    ]);

    console.log(`✓ 人员信息更新成功: ${processedData.chinese_name}`);

    res.json({
      success: true,
      message: '更新成功'
    });
  } catch (error) {
    console.error('更新人员信息失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/personnel/fix-education/:id
 * 修复单条记录的教育信息
 */
router.post('/fix-education/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    console.log(`修复教育信息，ID: ${id}`);

    // 获取记录
    const [records] = await pool.execute(`
      SELECT chinese_biography, graduate_school, education_level
      FROM processed_personnel
      WHERE raw_personnel_id = ?
    `, [id]);

    if (records.length === 0) {
      return res.status(404).json({
        success: false,
        message: '记录不存在'
      });
    }

    const record = records[0];
    
    if (!record.chinese_biography) {
      return res.json({
        success: false,
        message: '缺少中文简介，无法修复'
      });
    }

    // 调用AI修复教育信息
    const fixResult = await llmService.fixEducationInfo(record.chinese_biography);

    if (fixResult.success) {
      // 更新数据库
      await pool.execute(`
        UPDATE processed_personnel
        SET 
          graduate_school = ?,
          education_level = ?,
          updated_at = NOW()
        WHERE raw_personnel_id = ?
      `, [
        fixResult.graduate_school,
        fixResult.education_level,
        id
      ]);

      console.log(`✓ 教育信息已修复: ${fixResult.graduate_school} - ${fixResult.education_level}`);

      res.json({
        success: true,
        message: '教育信息修复成功',
        data: {
          graduate_school: fixResult.graduate_school,
          education_level: fixResult.education_level,
          education_year: fixResult.education_year,
          reason: fixResult.reason
        }
      });
    }
  } catch (error) {
    console.error('修复教育信息失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/personnel/fix-education
 * 批量修复所有记录的教育信息
 */
router.post('/fix-education', async (req, res) => {
  try {
    console.log('\n========== 开始批量修复教育信息 ==========');

    // 获取所有已审核通过的记录
    const [records] = await pool.execute(`
      SELECT 
        r.id as raw_id,
        p.chinese_name,
        p.english_name,
        p.graduate_school as current_school,
        p.education_level as current_level,
        p.chinese_biography
      FROM raw_personnel r
      INNER JOIN processed_personnel p ON r.id = p.raw_personnel_id
      WHERE r.audit_status = 'approved' AND p.chinese_biography IS NOT NULL
      ORDER BY r.id
    `);

    console.log(`找到${records.length}条记录需要检查`);

    const results = {
      total: records.length,
      success: 0,
      failed: 0,
      updated: 0,
      unchanged: 0,
      errors: []
    };

    // 逐条处理
    for (const record of records) {
      try {
        console.log(`\n处理: ${record.chinese_name || record.english_name} (ID: ${record.raw_id})`);
        console.log(`当前: ${record.current_school} - ${record.current_level}`);

        // 调用AI修复教育信息
        const fixResult = await llmService.fixEducationInfo(record.chinese_biography);

        if (fixResult.success) {
          // 检查是否需要更新
          const needUpdate = 
            fixResult.graduate_school !== record.current_school ||
            fixResult.education_level !== record.current_level;

          if (needUpdate) {
            // 更新数据库
            await pool.execute(`
              UPDATE processed_personnel
              SET 
                graduate_school = ?,
                education_level = ?,
                updated_at = NOW()
              WHERE raw_personnel_id = ?
            `, [
              fixResult.graduate_school,
              fixResult.education_level,
              record.raw_id
            ]);

            console.log(`✓ 已更新: ${fixResult.graduate_school} - ${fixResult.education_level}`);
            results.updated++;
          } else {
            console.log(`○ 无需更新`);
            results.unchanged++;
          }
          
          results.success++;
        }

        // 延迟避免请求过快
        await new Promise(resolve => setTimeout(resolve, 500));

      } catch (error) {
        console.error(`✗ 处理失败: ${error.message}`);
        results.failed++;
        results.errors.push({
          id: record.raw_id,
          name: record.chinese_name || record.english_name,
          error: error.message
        });
      }
    }

    console.log('\n========== 批量修复完成 ==========');
    console.log(`总计: ${results.total}`);
    console.log(`成功: ${results.success}`);
    console.log(`更新: ${results.updated}`);
    console.log(`未变: ${results.unchanged}`);
    console.log(`失败: ${results.failed}`);

    res.json({
      success: true,
      message: '批量修复完成',
      results
    });
  } catch (error) {
    console.error('批量修复教育信息失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

/**
 * POST /api/personnel/reprocess/:id
 * 重新解析单条记录
 */
router.post('/reprocess/:id', async (req, res) => {
  const processService = require('../services/processService');
  
  try {
    const { id } = req.params;
    
    console.log(`\n========== 开始重新解析记录 ID: ${id} ==========`);

    // 1. 获取原始记录
    const [rawRecords] = await pool.execute(
      'SELECT * FROM raw_personnel WHERE id = ?',
      [id]
    );

    if (rawRecords.length === 0) {
      return res.status(404).json({
        success: false,
        message: '记录不存在'
      });
    }

    const rawRecord = rawRecords[0];
    console.log(`找到原始记录: ${rawRecord.name}`);

    // 2. 检查是否已有处理后的记录
    const [processedRecords] = await pool.execute(
      'SELECT id FROM processed_personnel WHERE raw_personnel_id = ?',
      [id]
    );

    // 3. 如果已有处理后的记录，先删除
    if (processedRecords.length > 0) {
      console.log('删除旧的处理后记录...');
      await pool.execute(
        'DELETE FROM processed_personnel WHERE raw_personnel_id = ?',
        [id]
      );
    }

    // 4. 重置原始记录的处理状态
    await pool.execute(
      'UPDATE raw_personnel SET process_status = ?, process_time = NULL, process_error = NULL WHERE id = ?',
      ['pending', id]
    );

    // 5. 重新处理记录
    console.log('开始重新处理记录...');
    const result = await processService.processSingleRecord(rawRecord);

    if (result.success) {
      console.log('✓ 重新解析成功');
      
      // 6. 获取新的处理后数据返回给前端
      const [newProcessedRecords] = await pool.execute(
        'SELECT * FROM processed_personnel WHERE raw_personnel_id = ?',
        [id]
      );

      res.json({
        success: true,
        message: '重新解析成功',
        data: newProcessedRecords[0] || null
      });
    } else {
      throw new Error(result.error || '处理失败');
    }

  } catch (error) {
    console.error('✗ 重新解析失败:', error.message);
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

module.exports = router;

